"""
Case Type   : openGauss 支持忽略PLSQL间的依赖进行创建
Case Name   : postgresql.conf文件修改参数值
Create At   : 2023.09.12
Owner       : zhanghuan96
Description :
    1. postgresql.conf文件设置参数值
    2. 清理环境
Expect      :
    1. 成功
    2. 成功
History     :
"""
import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class PlpgsqlDependency(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.constant = Constant()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_node = Node('PrimaryDbUser')

    def test_guc(self):
        text = '--step1:postgresql.conf文件设置参数值;expect:成功--'
        self.log.info(text)
        sed_cmd = f"sed -i '$a\\behavior_compat_options=plpgsql_dependency' " \
                  f"{macro.DB_INSTANCE_PATH}/postgresql.conf"
        self.log.info(sed_cmd)
        sql_res = self.pri_node.sh(sed_cmd).result()
        self.log.info(sql_res)
        msg = self.pri_sh.restart_db_cluster()
        self.log.info(msg)
        status = self.pri_sh.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status,
                        '执行失败:' + text)
        sql_cmd = "show behavior_compat_options"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertEqual('plpgsql_dependency',
                         sql_res.splitlines()[-2].strip(),
                         '查询失败')

    def tearDown(self):
        text = '----step2:清理环境;expect:成功----'
        self.log.info(text)
        sed_cmd = f"source {macro.DB_ENV_PATH};" \
                  f"sed -i '$d' {macro.DB_INSTANCE_PATH}/postgresql.conf"
        self.log.info(sed_cmd)
        sql_res = self.pri_node.sh(sed_cmd).result()
        self.log.info(sql_res)
        msg = self.pri_sh.restart_db_cluster()
        self.log.info(msg)
        status = self.pri_sh.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status,
                        '执行失败:' + text)
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
